package com.weiyirong99.crm.app.ui;

import static org.litepal.LitePalApplication.getContext;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.tencent.mmkv.MMKV;
import com.weiyirong99.crm.app.R;
import com.weiyirong99.crm.app.api.Url;
import com.weiyirong99.crm.app.base.BaseActivity;
import com.weiyirong99.crm.app.bean.PhoneListBean;


import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.stream.Collectors;


/**
 * author  by  Canrom7 .
 * CreateDate 2021/8/30 11:46
 * Class LoginActivity
 */
public class AddCustsActivity extends BaseActivity implements View.OnClickListener {


    private android.widget.ImageView ivBack;
    private android.widget.ImageView ivCommit;
    private android.widget.RelativeLayout switchType;
    private android.widget.RelativeLayout switchType1;
    private android.widget.TextView tvtype;
    private android.widget.TextView tvtype1;
    private android.widget.TextView tv_add;
    private android.widget.TextView que_dh;
    private View switch_ph;
    private android.widget.TextView tvPhone;
    private android.widget.EditText evname;
    private android.widget.MultiAutoCompleteTextView tvdetail;
    private String url;
    private String phonne;
    private android.widget.RelativeLayout rlTitle;
    private android.widget.TextView tvTitle;
    private android.widget.ImageView currentImg1;
    private android.widget.TextView tvCname1;
    private android.widget.RelativeLayout switchPh;
    private android.widget.ImageView tubiao01;
    private android.widget.TextView queDh;
    private android.widget.RelativeLayout switchKehu;
    private android.widget.ImageView tubiao;
    private android.widget.TextView queTitle;
    private android.widget.RelativeLayout switchHelp;
    private android.widget.ImageView helpIcon;
    private android.widget.TextView helpTitle;
    private android.widget.RadioGroup homeRg;
    private android.widget.RadioButton rbFl;
    private android.widget.RadioButton rbDl;
    private android.widget.RadioButton rbZl;
    private android.widget.RadioButton rbOff;
    private android.widget.TextView tvAdd;

    @Override
    public int getLayout() {
        return R.layout.activity_addcust;
    }

    private String tid = null;
    private String pid = null;

    private String name = null;
    private String remark = "";
    private int type = 0;
    private int clientType = 0;

    private String phone = null;

    private boolean auto = false;


    private ClipboardManager cm;
    private ClipData mClipData;

    @Override
    public void initParms(Bundle parms) {


    }


    @Override
    public void initView() {
        phonne = getIntent().getStringExtra("phone");
        ivBack = $(R.id.iv_back);
        ivCommit = $(R.id.iv_commit);
        tv_add = $(R.id.tv_add);
        switch_ph = $(R.id.switch_ph);
        tvPhone = $(R.id.tv_phone);
        switchType1 = $(R.id.switch_type1);
        tvtype1 = $(R.id.tvtype1);
        que_dh = $(R.id.que_dh);
        evname = $(R.id.evname);
        tvdetail = $(R.id.tvdetail);
        ivBack.setOnClickListener(this);
        tv_add.setOnClickListener(this);
        ivCommit.setOnClickListener(this);
//        switchType.setOnClickListener(this);
        switchType1.setOnClickListener(this);
        tvPhone.setText(dealPhoneNumber(phonne));

        homeRg = (RadioGroup) findViewById(R.id.home_rg);
        rbFl = (RadioButton) findViewById(R.id.rb_fl);
        rbDl = (RadioButton) findViewById(R.id.rb_dl);
        rbZl = (RadioButton) findViewById(R.id.rb_zl);
        rbOff = (RadioButton) findViewById(R.id.rb_off);
        new Thread(new Runnable() {
            @Override
            public void run() {
                getCallHistoryList(AddCustsActivity.this, 1);
            }
        }).start();

        homeRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {
                    case R.id.rb_dl:
//                        isClick = 0;
                        tvdetail.setText("直接挂断");

                        rbDl.setBackground(getActivity().getResources().getDrawable(R.drawable.server_bt2));
                        rbDl.setTextColor(getActivity().getResources().getColor(R.color.colorBg));
                        rbFl.setBackground(getActivity().getResources().getDrawable(R.drawable.server));
                        rbFl.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
                        rbZl.setBackground(getActivity().getResources().getDrawable(R.drawable.server));
                        rbZl.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
                        rbOff.setBackground(getActivity().getResources().getDrawable(R.drawable.server));
                        rbOff.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
                        break;
                    case R.id.rb_fl:
//                        isClick = 2;
                        tvdetail.setText("无人接听");
                        rbFl.setBackground(getActivity().getResources().getDrawable(R.drawable.server_bt2));
                        rbFl.setTextColor(getActivity().getResources().getColor(R.color.colorBg));
                        rbDl.setBackground(getActivity().getResources().getDrawable(R.drawable.server));
                        rbDl.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
                        rbZl.setBackground(getActivity().getResources().getDrawable(R.drawable.server));
                        rbZl.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
                        rbOff.setBackground(getActivity().getResources().getDrawable(R.drawable.server));
                        rbOff.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
                        break;
                    case R.id.rb_zl:
//                        isClick = 3;
                        tvdetail.setText("不需要");
                        rbZl.setBackground(getActivity().getResources().getDrawable(R.drawable.server_bt2));
                        rbZl.setTextColor(getActivity().getResources().getColor(R.color.colorBg));
                        rbDl.setBackground(getActivity().getResources().getDrawable(R.drawable.server));
                        rbDl.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
                        rbFl.setBackground(getActivity().getResources().getDrawable(R.drawable.server));
                        rbFl.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
                        rbOff.setBackground(getActivity().getResources().getDrawable(R.drawable.server));
                        rbOff.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
                        break;

                    case R.id.rb_off:
//                        isClick = 3;

                        tvdetail.setText("关机");
                        rbOff.setBackground(getActivity().getResources().getDrawable(R.drawable.server_bt2));
                        rbOff.setTextColor(getActivity().getResources().getColor(R.color.colorBg));
                        rbZl.setBackground(getActivity().getResources().getDrawable(R.drawable.server));
                        rbZl.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
                        rbDl.setBackground(getActivity().getResources().getDrawable(R.drawable.server));
                        rbDl.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
                        rbFl.setBackground(getActivity().getResources().getDrawable(R.drawable.server));
                        rbFl.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
                        break;
                }
            }
        });

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back: {//返回
                onBackPressed();
                break;
            }
            case R.id.switch_type1: {//呼叫类型
                slectType();
                break;
            }
            case R.id.iv_commit:
            case R.id.tv_add: {//点击添加

                addCust();
                break;
            }
        }
    }


    private void slectType() {
//        final String[] items = new String[]{"呼叫成功", "未接通", "拨通秒挂", "已关机", "空号"};
//        Map<String, Integer> map = new HashMap<>();
//        map.put("呼叫成功", 2);
//        map.put("拨通秒挂", 3);
//        map.put("空号", 4);
//        map.put("已关机", 5);
//        map.put("未接听", 6);
//        new QMUIDialog.MenuDialogBuilder(getActivity())
//                .setSkinManager(QMUISkinManager.defaultInstance(this))
//                .addItems(items, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        type = map.get(items[which]);
//                        tvtype1.setText(items[which]);
//                    }
//                })
//                .create(mCurrentDialogStyle).show();
        new XPopup.Builder(this)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .asBottomList("", new String[]{"呼叫成功", "未接通", "拨通秒挂", "已关机", "空号"},
                        null, -1,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                phone = text;
                                tvtype1.setText(text);

                            }
                        })
                .show();
    }

    private void addCust() {
        name = evname.getText().toString();
        remark = tvdetail.getText().toString();

        long id = MMKV.defaultMMKV().decodeInt("companyId");
        int customer_id = getIntent().getIntExtra("customer_id", 0);
//        long customerid = MMKV.defaultMMKV().decodeInt("customerid");
        url = Url.BaseUrl + "/api/company/" + id + "/customers/" + customer_id + "/events?type=COMMENT&comment=" + remark;
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("pool", "BIZ");
        JSONObject jsonObject = new JSONObject(dataMap);
        OkGo.<String>post(url)
                .tag(AddCustsActivity.this)
                .headers("Authorization", MMKV.defaultMMKV().decodeString("token"))
                .upJson(jsonObject)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("WG", "onSuccess: " + response.body());
                        if (response.code() == 200) {
                            new MaterialDialog.Builder(getActivity())
                                    .title("提交跟进成功")
                                    .positiveText("确认")
                                    .cancelable(false)
                                    .onPositive((dialog, which) -> {
                                        dialog.dismiss();
                                        finish();
                                    })
                                    .onNegative((dialog, which) -> {
                                        dialog.dismiss();
                                    })
                                    .show();
                        } else {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body());
                                String message = jsonObject.getString("message");
                                Log.e("wg", "error: " + message);
                                ts(message);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.e("WG", "onError: ");
                        ts(response.message());

                    }
                });

    }


    @Override
    public BaseActivity getActivity() {
        return AddCustsActivity.this;
    }


    private static Boolean mIsExit = false;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void exitBy2Click() {
        Timer tExit;
        if (!mIsExit) {
            mIsExit = true; // 准备退出
            Toast.makeText(this, "再按关闭跟进页面", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    mIsExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            finish();
        }
    }

    private String dealPhoneNumber(String phoneNumber) {
        if (!TextUtils.isEmpty(phoneNumber)) {
            int len = phoneNumber.length();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < len; i++) {
                if (i > 2 && i < 7) {
                    builder.append("*");
                } else {
                    builder.append(phoneNumber.charAt(i));
                }

                if (i == 2 || i == 6) {
                    if (i != len - 1)
                        builder.append(" ");
                }
            }

            return builder.toString();
        }
        return null;
    }

    /**
     * 利用系统CallLog获取通话历史记录
     *
     * @param activity
     * @param num      要读取记录的数量
     * @return
     */
    public void getCallHistoryList(Activity activity, int num) {
        Cursor cs;
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_CALL_LOG)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.READ_CALL_LOG}, 1000);

        }
        cs = activity.getContentResolver().query(CallLog.Calls.CONTENT_URI, //系统方式获取通讯录存储地址
                new String[]{
                        CallLog.Calls.CACHED_NAME,  //姓名
                        CallLog.Calls.NUMBER,    //号码
                        CallLog.Calls.TYPE,  //呼入/呼出(2)/未接
                        CallLog.Calls.DATE,  //拨打时间
                        CallLog.Calls.DURATION,   //通话时长
                }, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
        int i = 0;
        if (cs != null && cs.getCount() > 0) {
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String date_today = simpleDateFormat.format(date);
            for (cs.moveToFirst(); (!cs.isAfterLast()) && i < num; cs.moveToNext(), i++) {
                String callName = cs.getString(0);  //名称
                String callNumber = cs.getString(1);  //号码
                //如果名字为空，在通讯录查询一次有没有对应联系人
                if (callName == null || callName.equals("")) {
                    String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME};
                    //设置查询条件
                    String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + "='" + callNumber + "'";
                    Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            cols, selection, null, null);
                    int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
                    if (cursor.getCount() > 0) {
                        cursor.moveToFirst();
                        callName = cursor.getString(nameFieldColumnIndex);
                    }
                    cursor.close();
                }
                //通话类型
                int callType = Integer.parseInt(cs.getString(2));
                String callTypeStr = "";
                switch (callType) {
                    case CallLog.Calls.INCOMING_TYPE:
                        callTypeStr = "打入";
                        break;
                    case CallLog.Calls.OUTGOING_TYPE:
                        callTypeStr = "打出";
                        break;
                    case CallLog.Calls.MISSED_TYPE:
                        callTypeStr = "未接";
                        break;
                    default:
                        //其他类型的，例如新增号码等记录不算进通话记录里，直接跳过
                        Log.i("ssss", "" + callType);
                        i--;
                        continue;
                }
                //拨打时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
                Date callDate = new Date(Long.parseLong(cs.getString(3)));
                String callDateStr = sdf.format(callDate);

//                if (callDateStr.equals(date_today)) { //判断是否为今天
//                    sdf = new SimpleDateFormat("HH:mm");
//                    callDateStr = sdf.format(callDate);
//                } else if (date_today.contains(callDateStr.substring(0, 7))) { //判断是否为当月
//                    sdf = new SimpleDateFormat("dd");
//                    int callDay = Integer.valueOf(sdf.format(callDate));
//
//                    int day = Integer.valueOf(sdf.format(date));
//                    if (day - callDay == 1) {
//                        callDateStr = "昨天";
//                    } else {
//                        sdf = new SimpleDateFormat("MM-dd");
//                        callDateStr = sdf.format(callDate);
//                    }
//                } else if (date_today.contains(callDateStr.substring(0, 4))) { //判断是否为当年
//                    sdf = new SimpleDateFormat("MM-dd");
//                    callDateStr = sdf.format(callDate);
//                }

                //通话时长
                int callDuration = Integer.parseInt(cs.getString(4));
//                int min = callDuration / 60;
//                int sec = callDuration % 60;
//                String callDurationStr = "";
//                if (sec > 0) {
//                    if (min > 0) {
//                        callDurationStr = min + "分" + sec + "秒";
//                    } else {
//                        callDurationStr = sec + "秒";
//                    }
//                }

                /**
                 * callName 名字
                 * callNumber 号码
                 * callTypeStr 通话类型
                 * callDateStr 通话日期
                 * callDurationStr 通话时长
                 * 请在此处执行相关UI或存储操作，之后会查询下一条通话记录
                 */
                Log.e("WG", "callName :" + callName);
                Log.e("WG", "callNumber :" + callNumber);
                Log.e("WG", "callTypeStr :" + callTypeStr);
                Log.e("WG", "callDateStr :" + callDateStr);
                Log.e("WG", "callDurationStr :" + callDuration);

                name = evname.getText().toString();
                remark = tvdetail.getText().toString();

                long id = MMKV.defaultMMKV().decodeInt("companyId");
                int customer_id = getIntent().getIntExtra("customer_id", 0);
//        long customerid = MMKV.defaultMMKV().decodeInt("customerid");
                url = Url.BaseUrl + "/api/company/" + id + "/user-call?mobile=" + callNumber + "&createdAt=" + callDateStr + "&duration=" + callDuration;
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("pool", "BIZ");
                JSONObject jsonObject = new JSONObject(dataMap);
                OkGo.<String>post(url)
                        .tag(AddCustsActivity.this)
                        .headers("Authorization", MMKV.defaultMMKV().decodeString("token"))
                        .upJson(jsonObject)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {

                                Log.e("WG", "onSuccess: " + response.body());
                                if (response.code() == 200) {

                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                Log.e("WG", "onError: " + response.body());
                                ts(response.message());
                            }
                        });
            }
        }
    }
}
